﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using StockFinder.Model;

namespace StockFinder.Services.Extractors.Yahoo
{
    public class YahooCsvHistoricPricesExtractor
    {
        public List<DailyPrice> GetHistoricPrices(string location)
        {
            List<DailyPrice> prices = new List<DailyPrice>();

            if (File.Exists(location))
            {
                string source = string.Empty;

                using (StreamReader sr = new StreamReader(location))
                {
                    source = sr.ReadToEnd();
                }

                if (!string.IsNullOrEmpty(source))
                {
                    var lines = source.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                    foreach (var line in lines)
                    {
                        if (!line.Contains("Date") && !string.IsNullOrEmpty(line) )
                        {
                            var cells = line.Split(new[] { "," }, StringSplitOptions.None);

                            prices.Add(new DailyPrice()
                            {
                                PriceDate = Convert.ToDateTime(cells[0]),
                                Open = Convert.ToDecimal(cells[1]),
                                High = Convert.ToDecimal(cells[2]),
                                Low = Convert.ToDecimal(cells[3]),
                                Close = Convert.ToDecimal(cells[4]),
                                Volume = Convert.ToInt64(cells[5]),
                                AdjustedClose = Convert.ToDecimal(cells[6]),
                            });
                        }
                    }
                }
            }

            return prices;
        }
    }
}
